package com.remoter.api.cluster.support;

import java.util.List;

import com.remoter.api.cluster.ILoadBalance;
import com.remoter.api.context.support.Exporter;
import com.remoter.api.context.support.Importer;
import com.remoter.api.util.Final;

public abstract class AbstractLoadBalance implements ILoadBalance{

	@Override
	public Exporter select(Importer importer,List<Exporter> exporters){
		if(exporters.size() == 1){
			return exporters.get(0);
		}
		return this.doSelect(importer,exporters);
	}
	
	public abstract Exporter doSelect(Importer importer,List<Exporter> exporters);
	
	protected int getWeight(Exporter exporter){
		int weight = exporter.getWeight() <= 0 ? Final.D_LOADBALANCE_WEIGHT : exporter.getWeight();
		if(weight > 0){
			long timestamp = System.currentTimeMillis();
			if(timestamp > 0L){
				int uptime = (int)(System.currentTimeMillis() - timestamp);
				int warmup = (int)exporter.getStartTime();
				if(uptime > 0 && uptime < warmup){
					weight = calculateWarmupWeight(uptime, warmup, weight);
				}
			}
		}
		return weight;
	}
	
	protected static int calculateWarmupWeight(int uptime,int warmup,int weight){
		int ww = (int) ( (float) uptime / ( (float) warmup / (float) weight ) );
    	return ww < 1 ? 1 : (ww > weight ? weight : ww);
	}
	
}